package controllers

import (
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
	"travel/cache"
	"travel/models"
)

type TravelController struct {
	beego.Controller
}

func (c *TravelController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	title := c.GetString("title")
	content := c.GetString("content")
	price := c.GetString("price")

	if title == "" || content == "" || price == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "字段不能为空",
		}
		c.ServeJSON()
		return
	}
	travel := models.Travel{
		Title:   title,
		Content: content,
		Price:   price,
	}
	models.DB.Create(&travel)

	//查询添加的数据
	var travelData models.Travel
	models.DB.Where("title=?", title).First(&travelData)

	//将数据添加到缓存
	travel_redis_key := "travel_data_id" + strconv.Itoa(int(travelData.ID))
	cacheJson, _ := json.Marshal(travelData)
	cache.Rdb.Set(cache.Ctx, travel_redis_key, cacheJson, time.Hour*1)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
		"data": travel,
	}
	c.ServeJSON()
	return
}

// 列表
func (c *TravelController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var shopData []models.Travel

	shop_list_redis_key := "shop_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, shop_list_redis_key).Result() //获取缓存的列表数据

	if cacheData == "" {
		//从mysql查询数据
		models.DB.Find(&shopData)

		cacheJson, _ := json.Marshal(shopData)
		cache.Rdb.Set(cache.Ctx, shop_list_redis_key, cacheJson, time.Hour*1)
	} else {
		//从redis获取数据
		json.Unmarshal([]byte(cacheData), &shopData)
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"data": shopData,
		"msg":  "success",
	}
	c.ServeJSON()
	return
}

// 修改
func (c *TravelController) Update() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	title := c.GetString("title")
	content := c.GetString("content")
	price := c.GetString("price")

	if title == "" || content == "" || price == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"msg":  "字段不能为空",
		}
		c.ServeJSON()
		return
	}
	travel := models.Travel{
		Title:   title,
		Content: content,
		Price:   price,
	}
	models.DB.Where("id=?", id).Updates(&travel)
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "修改成功",
	}
	c.ServeJSON()
	return
}

// 删除
func (c *TravelController) Delete() {
	id, _ := c.GetInt("id")

	var travel models.Travel
	models.DB.Where("id=?", id).Delete(&travel)

	//删除缓存
	travel_redis_key := "travel_id" + strconv.Itoa(int(travel.ID))
	cache.Rdb.Del(cache.Ctx, travel_redis_key)

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}
